package control;

import entities.Folder;
import entities.LinkCollection;
import java.io.IOException;
import java.util.GregorianCalendar;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import util.ServletUtil;

@WebServlet(name="NewLinkCollection", urlPatterns={"/NewLinkCollection"})
public class NewLinkCollection extends HttpServlet {
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        // Form control
        boolean formSuccess = false;
        
        // JPA
        EntityManagerFactory fact = Persistence.createEntityManagerFactory("vh11_WebApplication1PU");
        EntityManager em = fact.createEntityManager();
        
        // The bean to save
        LinkCollection linkCollection = new LinkCollection();
        request.setAttribute("linkCollection", linkCollection);
        request.setAttribute("headJsUrls", new String[]{"js/newLinkCollection.js"});
        
        try {
            if(request.getMethod().equals("POST")) {
                try {
                    em.getTransaction().begin();
                    
                    Folder selectedFolder = em.find(Folder.class, ServletUtil.getLong(request.getParameter("folderId"), -1));
                    linkCollection.setParent(selectedFolder);
                    linkCollection.setName(request.getParameter("name"));
                    linkCollection.setLinks(request.getParameter("links"));
                    linkCollection.setDateCreated(new GregorianCalendar());
                    linkCollection.setDateModified(new GregorianCalendar());
                    
                    em.persist(linkCollection);
                    em.getTransaction().commit();
                    formSuccess = true;
                }
                catch(ConstraintViolationException ex) {
                    request.setAttribute("formErrors", ex.getConstraintViolations());
                }
            }
            else {
                long folderId = ServletUtil.getLong(ServletUtil.getCookie(request, "currentFolderId"), -1);
                Folder folder = em.find(Folder.class, folderId);
                linkCollection.setParent(folder);
            }
        }
        finally {
            em.close();
            fact.close();
        }
        
        if (formSuccess) {
            response.sendRedirect("NewLinkCollection?success=true");
        }
        else {
            RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/views/newLinkCollection.jsp");
            dispatcher.forward(request, response);
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
